package com.eboss2.sbs.http;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.eboss2.sbs.R;
import com.eboss2.sbs.config.Config;
import com.eboss2.sbs.myapplication.MyApplication;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.mytools.tool.security.MD5;
import com.mytools.tool.utils.LocalParasUtils;
import com.mytools.tool.utils.LogUtils;
import com.mytools.tool.utils.NetworkUtil;
import com.mytools.tool.utils.StringUtil;
import com.mytools.tool.utils.TimeUtil;
import com.tool.utils.utils.ALog;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


//import cz.msebera.android.httpclient.Header;
//import cz.msebera.android.httpclient.HttpEntity;

@SuppressWarnings("rawtypes")
public class HttpRequest {

	private AsyncHttpClient client;
	private Context context;
	private TextHttpResponseHandler responseHandler;
	private HttpCallback callback;

	public HttpRequest(final Context context, final HttpCallback callback) {
		this.context = context;
		this.client = MyApplication.getmInstance().getHttpclient();
		this.client.setTimeout(Config.HTTP_TIME_OUT);
		this.callback = callback;
		
		this.responseHandler = new TextHttpResponseHandler() {

			@Override
			public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
//				Log.e("http", ""+statusCode+"\t"+throwable.getMessage());
				ALog.json("HttpUtil", ""+statusCode+"\t"+throwable.getMessage());
				if(callback == null){return;}
				if(statusCode==408){callback.onFailure(statusCode, "请求超时超时");}
				else callback.onFailure(statusCode, statusCode+" "+throwable.getMessage());
			}
			
			@SuppressWarnings("unchecked")
			@Override
			public void onSuccess(int statusCode, Header[] headers, String responseString) {
				
				if(Config.PRINT_LOG){
//					Log.e("http","responseString:"+ responseString);
					ALog.json("HttpUtil", responseString);
				}
				if(callback == null){return;}
				HttpResponse data;
				try {
					data = (null == callback.getTypeToken()) ? HttpJsonParser.fromJson(responseString) : HttpJsonParser.fromJson(responseString, callback.getTypeToken());
				} catch (Exception e) {
//					Log.e("parse_data_failed", "parse_data_failed..."+e.getMessage());
					ALog.json("HttpUtil", "parse_data_failed..."+e.getMessage());
					callback.onFailure(statusCode, context.getString(R.string.parse_data_failed));
					return;
				}
				if (null!=data.getCode()&&data.getCode().equals(Config.HTTP_OK)) {callback.onSuccess(statusCode, data.getResult());}
				else if (!TextUtils.isEmpty(data.getMsg())) {
					callback.onFailure(statusCode, data.getMsg());
				}
			}
			@Override
			public void onFinish() {
				if(callback == null){return;}
				callback.postLoad();
			}
			@Override
			public void onStart() {
				if(callback == null){return;}
				callback.preLoad();
			}
		};
	}

	public void get(String url) {
		if (!NetworkUtil.isNetworkAvailable(context)) {
			if(Config.PRINT_LOG){
//				Log.e("http", url);
				ALog.json("HttpUtil", url);
			}
			if(callback == null){return;}
			callback.onFailure(-1, context.getString(R.string.network_info));
			return;
		}
		client.get(url, responseHandler);
	}
	
	public void get(String url, RequestParams params) {
		if (!NetworkUtil.isNetworkAvailable(context)) {
			if(callback == null){return;}
			callback.onFailure(-1, context.getString(R.string.network_info));
			return;
		}
		client.get(url,params, responseHandler);
	}

	public void post(String url, RequestParams requestParams) {
		if (!NetworkUtil.isNetworkAvailable(context)) {
			if(callback == null){return;}
			callback.onFailure(-1, context.getString(R.string.network_info));
			return;
		}
		client.post(url, requestParams, responseHandler);
	}

	public void post(String url, HttpEntity entity) {
		if (!NetworkUtil.isNetworkAvailable(context)) {
			if(callback == null){return;}
			callback.onFailure(-1, context.getString(R.string.network_info));
			return;
		}
		client.post(context, url, entity, null, responseHandler);
	}
	
//	public void post(String url, Map<String, Object> params) {
//		JSONObject jsonParams = new JSONObject(params);
//		StringEntity entity;
//		try {
//			if(Config.PRINT_LOG){
//				Log.e("http", url);
//				Log.e("http", jsonParams.toString());
//			}
//			entity = new StringEntity(jsonParams.toString(), "UTF-8");
//			entity.setContentType("application/json;charset=UTF-8");
//		} catch (UnsupportedEncodingException e) {
//			if(callback == null){return;}
//			callback.onFailure(context.getString(R.string.load_data_failed));
//			return;
//		}
//		post(url, entity);
//	}
	
	//POST
	public void post(String url, Map<String, Object> params) {
		if (!NetworkUtil.isNetworkAvailable(context)) {
			if(callback == null){return;}
			callback.onFailure(-1, context.getString(R.string.network_info));
			return;
		}
		
		String xLoginDate = LocalParasUtils.getXLoginDate(context);
		if(StringUtil.isNull(xLoginDate)){}
		else {
			String nowDateStr = TimeUtil.getCurrentDateString("yyyyMMdd");
			if(!xLoginDate.equals(nowDateStr)){
				callback.onFailure(-1, "登录失效，请重启应用");
				return;
			}
		}
		
		JSONObject jsonParams = null;
		StringEntity entity;
		
		try {
			ArrayList<String> keys = new ArrayList<String>();
			for (Iterator<String> it = params.keySet().iterator(); it.hasNext();) {
				keys.add(it.next());
			}
			String tmp = "";
			keys = StringUtil.getSortAsc(keys);
			for (int i = 0; i < keys.size(); i++) {
				Object obj = params.get(keys.get(i));
				if(obj!=null){tmp = tmp + obj.toString();}
			}
			
			Map<String, Object> final_params = new HashMap<String, Object>();
			final_params.put("cmd", url);
			LogUtils.e(tmp+Config.key);
			String verify =  MD5.Md5(tmp+Config.key);
			params.put("verify", verify);
			final_params.put("params", params);
			
			jsonParams = new JSONObject(final_params);
			
			if(Config.PRINT_LOG){
				Log.e("http", Config.BasePath_POS+"?rand="+(new Date()).getTime());
				Log.e("http", jsonParams.toString());
				ALog.json("HttpUtil", Config.BasePath_POS+"?rand="+(new Date()).getTime());
				ALog.json("HttpUtil", jsonParams.toString());
			}
			
			entity = new StringEntity(jsonParams.toString(), "UTF-8");
			entity.setContentType("application/json;charset=UTF-8");
			
		} catch (UnsupportedEncodingException e) {
			if(callback == null){return;}
			callback.onFailure(-1, context.getString(R.string.load_data_failed));
			return;
		}
		post(Config.BasePath_POS+"?rand="+(new Date()).getTime(), entity);
	}
	
//	public void post_upgrade_pre(String url, Map<String, Object> params) {
//		JSONObject jsonParams = new JSONObject(params);
//		StringEntity entity;
//		try {
//			if(Config.PRINT_LOG){
//				Log.e("http", url);
//				Log.e("http", jsonParams.toString());
//			}
//			entity = new StringEntity(jsonParams.toString(), "UTF-8");
//			entity.setContentType("application/json;charset=UTF-8");
//		} catch (UnsupportedEncodingException e) {
//			if(callback == null){return;}
//			callback.onFailure(context.getString(R.string.load_data_failed));
//			return;
//		}
//		post(url, entity);
//	}
	
//	public void postByArrParam(String url,String content) {
//		StringEntity entity;
//		try {
//			entity = new StringEntity(content, "UTF-8");
//			entity.setContentType("application/json;charset=UTF-8");
//		} catch (UnsupportedEncodingException e) {
//			if(callback == null){return;}
//			callback.onFailure(context.getString(R.string.load_data_failed));
//			return;
//		}
//		post(url, entity);
//	}
//	
//	public void post(String url, Map<String, Object> params, Boolean is) {
//		Gson gson = new Gson();
//		String gsonString = gson.toJson(params);
//		StringEntity entity;
//		try {
//			entity = new StringEntity(gsonString, "UTF-8");
//			entity.setContentType("application/json;charset=UTF-8");
//		} catch (UnsupportedEncodingException e) {
//			if(callback == null){return;}
//			callback.onFailure(context.getString(R.string.load_data_failed));
//			return;
//		}
//		post(url, entity);
//	}
//	
//	public void post(String url) {
//		HttpEntity entity = null;
//		if(Config.PRINT_LOG){Log.e("http", url);}
//		post(url, entity);
//	}
	
}
